import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import os
import numpy as np
import PIL.Image as Image

"""
wordcloud词云  
"""

string = 'Importance of relative word frequencies for font-size. With relative_scaling=0, only word-ranks are considered. With relative_scaling=1, a word that is twice as frequent will have twice the size. If you want to consider the word frequencies and not only their rank, relative_scaling around .5 often looks good.'
# 做成网上那样有不同形状的，在wordcloud中提供了一个参数mask，他可以让你指定你想绘制的图片，不过必须是白底的，他会在你非白底的地方填充上文字
alice_coloring = np.array(Image.open('background.jpg'))
# 生成词云
my_wordcloud = WordCloud(background_color="white", max_words=2000,
                         mask=alice_coloring,max_font_size=40, random_state=42,
                         font_path='./msyh.ttf').generate(string)

image_colors = ImageColorGenerator(alice_coloring)
# plt用来显示图片
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()

my_wordcloud.to_file('weibo_xiong01.png')